package com.sunlee.common.core.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @author sunulee
 */
public class StringUtil {

    public static String subString(String str, int start, int end) {
        if (StringUtils.isBlank(str)) {
            return str;
        }
        if (str.length() > end) {
            return str.substring(start, end);
        }
        return str;
    }

    public static String decodePath(String str) {
        if (StringUtils.isBlank(str)) {
            return null;
        }
        try {
            return URLDecoder.decode(str, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            return str;
        }
    }

    /**
     * 去除首尾指定字符
     *
     * @param str     字符串
     * @param element 指定字符
     * @return 去除首尾后的字符
     */
    public static String trimFirstAndLastChar(String str, String element) {
        boolean beginIndexFlag;
        boolean endIndexFlag;
        do {
            int beginIndex = str.indexOf(element) == 0 ? 1 : 0;
            int endIndex = str.lastIndexOf(element) + 1 == str.length() ? str.lastIndexOf(element) : str.length();
            str = str.substring(beginIndex, endIndex);
            beginIndexFlag = (str.indexOf(element) == 0);
            endIndexFlag = (str.lastIndexOf(element) + 1 == str.length());
        } while (beginIndexFlag || endIndexFlag);
        return str;
    }

    /**
     * 截取指定字符之后的字符
     *
     * @param str     字符串
     * @param element 指定字符
     * @return 截取后的字符
     */
    public static String subCharBefore(String str, String element) {
        return str.substring(str.indexOf(element) + 1);
    }

    public static String subLastCharCentre(String str, String start, String end) {
        return str.substring(str.lastIndexOf(start) + 1, str.lastIndexOf(end));
    }
    /**
     * 过滤非数字
     * @param str
     * @return
     */
    public static String getNumeric(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }
}
